import Vue from 'vue';

import axios from 'axios'
import Qs from 'qs'
import doc from './doc'
import root from './root'
import user from './user'
import trademark from './trademark'
import muneConfig from './mune-config'

import tools from '@/server/storage.server'

const host = process.env.VUE_APP_HOST_API;
// 实例化 ajax请求对象
const ajaxinstance = axios.create({
  baseURL: host,
  timeout: 5000,
  //   headers: {
  //     // responseType: 'json',
  //     // 'Content-Type': 'application/json'
  //   }
  transformRequest: [function (data = {}) {
    data = Qs.stringify(data)
    return data
  }],
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

})

// 添加拦截器，处理 公用请求参数，和通用请求头部
ajaxinstance
  .interceptors
  .request
  .use((config) => {
    const token = tools.get('token')
    if (token) {
      config.headers['token'] = token
    }
    return config
  }, (error) => {
    Promise.reject(error)
  })

// 请求响应拦截器
ajaxinstance
  .interceptors
  .response
  .use((response) => {
    if (response.data.code !== 0) {
      Vue.prototype.$message.error(response.data.message || `${response.data.errorData[0].field} ${response.data.errorData[0].message}`);
    }
    return response.data
  }, (error) => {
    Vue.prototype.$message.error(error.data.message || `${error.data.errorData[0].field} ${error.data.errorData[0].message}`);
    return Promise.reject(error)
  }, (error) => {
    Vue.prototype.$message.error(error.data.message || `${error.data.errorData[0].field} ${error.data.errorData[0].message}`);
    return Promise.reject(error)
  })

/**
 * [API api接口封装]
 * @type {Object}
 */
const API = {
  ...doc(ajaxinstance),
  ...root(ajaxinstance),
  ...user(ajaxinstance),
  ...trademark(ajaxinstance),
  ...muneConfig(ajaxinstance)
}

export default API
